package cn.yunhe;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.data.redis.core.RedisTemplate;

/**
 * Created by zs on 2017/11/30.
 * 使用Spring测试Redis字符串操作
 */
public class Demo3 {

    @Test
    public void test1() {
        ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
        RedisTemplate redisTemplate = ac.getBean(RedisTemplate.class);

        //设值
        redisTemplate.opsForValue().set("key1", "value1");
        redisTemplate.opsForValue().set("key2", "value2");

        //通过key获取值
        String value1 = (String) redisTemplate.opsForValue().get("key1");
        System.out.println(value1);

        //通过key删除值
        redisTemplate.delete("key1");

        //求长度
        Long length = redisTemplate.opsForValue().size("key2");
        System.out.println(length);

        //设置新值，并返回旧值
        String oldValue2 = (String) redisTemplate.opsForValue().getAndSet("key2", "new_value2");
        System.out.println(oldValue2);

        //求子串
        String rangeValue = redisTemplate.opsForValue().get("key2", 0, 3);
        System.out.println(rangeValue);

        //追加到末尾，返回新长度
        int newLen = redisTemplate.opsForValue().append("key2", "_app");
        System.out.println(newLen);

        //获取追加后的字符串
        String appendValue2 = (String) redisTemplate.opsForValue().get("key2");
        System.out.println(appendValue2);


    }
}
